var autoSearch = null;

var MY_ADDITIVE_FEE = (function() {
	function loadItem(usageValue) {
		WeKnow.loading();
		$.ajax({ 
			type: "POST", 
			url: "wncrm_clinic_additive_fee_conf.do/load", 
			dataType: "json",
			data: {
				usageValue: usageValue
			},
			async: false,
			success: function(data) {
				$('tbody#itemGroup').empty();
				
				var items = data.items;
				if (items && items.length) {
					$(items).each(function(idx, item) {
						var g = {
							goodsId: item.itemId
							,goodsType: item.prescriptionType
							,amount: item.amount
							,goodsName: item.itemName
							,goodsUnit2: item.itemUnitText
						};
						MY_ADDITIVE_FEE.createOneGoodsHtml(g);
					});
				}
			},
			error: function() {
				WeKnow.systemMsg("系统异常");
			}
		});
		WeKnow.closeLoading();
	}
	
	function saveOrUpdate() {
		var params = {};
		params.chargeList = [];
		params.userages = [];
		
		$('ul#useages>li.active').each(function() {
			params.userages.push($(this).data('useageid') + '');
		});
		
		var hasErr = false;
		$('tbody#itemGroup>tr').each(function() {
			var $that = $(this);
			var charge = {};
			charge.prescriptionType = $that.data('prescriptiontype');
			charge.itemId = $that.data('itemid');
			charge.amount = $that.find('input[name="amount"]').val();
			if (!charge.amount.length) {
				WeKnow.errorMsg('请输入数量');
				$that.find('input[name="amount"]').focus();
				hasErr = true;
				return false;
			} else if (!MY_VALIDATOR.isNumber(charge.amount)) {
	    		WeKnow.errorMsg('数字不正确');
	    		$that.find('input[name="amount"]').focus();
				hasErr = true;
				return false;
	    	}
			params.chargeList.push(charge);
		});
		
		if (hasErr) return false;
		
		WeKnow.loading();
		$.ajax({ 
			type: "POST", 
			url: "wncrm_clinic_additive_fee_conf.do/save", 
			dataType: "json",
			contentType: "application/json",
			data: JSON.stringify(params),
			async: false,
			success: function(data) {
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
				if (data.errcode == 0) {
					WeKnow.successMsg('保存成功');
				} else {
					WeKnow.systemMsg("系统异常");
				}
				
			},
			error: function() {
				WeKnow.systemMsg("系统异常");
			}
		});
		WeKnow.closeLoading();
	}
	
	/**
	 * 添加一项出库 药品耗材
	 */
	function createOneGoodsHtml(g) {
		var dumplicate = false;
		var $itemGroup = $('tbody#itemGroup');
		$itemGroup.find('tr').each(function(idx, tr) {
			var $tr = $(tr);
			if (g.goodsId == $tr.data('itemid') && g.goodsType == $tr.data('prescriptiontype')) {
				dumplicate = true;
				return false;
			}
		});
		if (dumplicate) {
			WeKnow.notifyMsg('重复数据');
			return false;
		}
		
		var e = '';
		e += '<tr style="height: 50px;"';
			e += ' data-prescriptiontype="' + g.goodsType + '"';
			e += ' data-itemid="' + g.goodsId + '"';
		e += '>';
			e += '<td>' + ($itemGroup.find('tr').length + 1) + '</td>';
			e += '<td>' + g.goodsName + (g.goodsType == 10 ? ' ' + g.goodsSpec : '') + '</td>';
			e += '<td>' + g.goodsUnit2 + '</td>';
			e += '<td><input type="text" maxlength="3" class="form-control output-sm" name="amount" autocomplete="off" value="' + (g.amount != null ? g.amount : '') + '" style="width: 150px;"></td>';
			e += '<td><button type="button" class="btn btn-link" name="delete">删除</button></td>';
		e += '</tr>';
		
		var $goods = $(e).appendTo('tbody#itemGroup');
		$goods.find('button[name="delete"]').on('click', function() {
			$(this).closest('tr').remove();
		});
		$goods.find('input[name="amount"]').on('blur', function() {
			var $that = $(this);
			if ($that.val().length && !MY_VALIDATOR.isNumber($that.val())) {
	    		WeKnow.errorMsg('数字不正确');
	    		$that.focus();
	    	}
		});
		$('input#goodsSearchTxt').val(''); // clear context
	}
	
	return {
		loadItem: loadItem
		,saveOrUpdate: saveOrUpdate
		,createOneGoodsHtml: createOneGoodsHtml
	}
})();

$(document).ready(function() {
	
	// 工作区域 高度调整
	(function() {
		var panelHeight = $(window).height() - 80;
		$("#rightPanel, #leftPanel").css({"max-height": (panelHeight) + "px", "min-height": (panelHeight) + "px"});
		$("#leftPanel ul#useages").css({"max-height": (panelHeight - 40) + "px", "min-height": (panelHeight - 40) + "px", "overflow-y": "auto"});
	})();
	
	// 用法选择
	var $useages = $('ul#useages'); 
	$useages.find('li').on('click', function() {
		var multConfSwith = $('input#multiConfSwitch').prop('checked');
		var $that = $(this);
		
		if (multConfSwith) { // 复选
			if ($that.hasClass('active')) {
				$that.removeClass('active');
			} else {
				$that.addClass('active');
				MY_ADDITIVE_FEE.loadItem($that.data('useageid'));
			}
		} else { // 单选
			$that.siblings('li').removeClass('active');
			$that.addClass('active');
			MY_ADDITIVE_FEE.loadItem($that.data('useageid'));
		}
	});
	
	// 自动检索药品耗材
	$('input#goodsSearchTxt').on('input click', function() {
		
		if (autoSearch) clearTimeout(autoSearch);
		
		var $that = $(this);
		$('ul.dropdown-menu.goods-dropdown-menu').remove();
		
		var searchKey = $.trim($that.val());
		if (searchKey.length) {
			autoSearch = setTimeout(function() {
				$.post(
					WeKnow.getRealPath() + '/wncrm_clinic_additive_fee_conf.do/mst_items/load',
					{
						searchKey: searchKey
					},
					function(data, status) {
						var goodsList = data.goodsList;
						if (goodsList && goodsList.length > 0) {
							var e = '<ul class="dropdown-menu goods-dropdown-menu" style="max-height: 250px; width: 300px; padding-top: 0px;padding-bottom: 0px; overflow-y:auto;">';
								e += '<li>';
									e += '<table class="table table-hover table-condensed" style="margin-bottom: 0px;">';
											e += '<thead class="bg-default" style="font-weight: 700;">';
												e += '<tr>';
													e += '<td width="25%">类型</td>';
													e += '<td width="50%">项目名称</td>';
													e += '<td width="25%">单价</td>';
												e += '</tr>';
											e += '</thead>';
											e += '<tbody></tbody>';
									e += '</table>'
								e += '</li>';
							e += '</ul>';
							var $goodsList = $that.after(e).next('ul.dropdown-menu.goods-dropdown-menu').show();
							$(goodsList).each(function(idx, g) {
								$((function() {
									var e = '';
									e += '<tr';
										if (idx == 0) {
											e += ' class="active"';
										}
									e += '>';
										e += '<td>';
											if (g.goodsType == 10) {
												e += '材料';
											} else {
												e += '诊疗项目';
											}
										e += '</td>';
										e += '<td>' + g.goodsName + '</td>';
										e += '<td>' + g.goodsUnit2 + '</td>';
									e += '</tr>';
									return e;
								})()).appendTo($goodsList.find('tbody')).on('click', function() {
									MY_ADDITIVE_FEE.createOneGoodsHtml(g);
								});
								
							});
							$('body').one('click', function() {
								$goodsList.remove();
							});
						}
					}
				)
			}, 300);
		}
	});
	
	
	// 保存信息
	$('button#save').on('click', function() {
		MY_ADDITIVE_FEE.saveOrUpdate();
	});
	
	// 选择第一个
	$('ul#useages>li:first').click();
});